package com.sgb.kjwl.view.ui.fragment.pick;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentPickAttentionBiddingListBinding;
import com.sgb.kjwl.di.pick.DaggerPickProjectComponent;
import com.sgb.kjwl.di.pick.PickProjectModule;
import com.sgb.kjwl.model.entity.BiddingEntity;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.pick.PickBidingAdapter;
import com.sgb.kjwl.view.widget.CommonCategoryFilterPopWindow;
import com.sgb.kjwl.view.widget.PickHallBidingPopWindow;
import com.sgb.kjwl.view.widget.pick.PickPopWindowView;
import com.sgb.kjwl.viewmodel.pick.PickAttentionBiddingListModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.util.PickSelectEntity;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

/**
 * 智能关注-招采-竞价
 */
public class PickAttentionBiddingListFragment extends AppFragment {

    @Inject
    PickAttentionBiddingListModel viewModel;
    private FragmentPickAttentionBiddingListBinding binding;
    private PickBidingAdapter pickingAdapter;

    private PickHallBidingPopWindow pickMoneyPopWindow;
    private CommonCategoryFilterPopWindow categoryFilterPopWindow;

    private boolean isChange2;
    private boolean isChange4;

    private List<PickSelectEntity> priceData = new ArrayList<>();
    private List<PickSelectEntity> typeData = new ArrayList<>();
    private List<PickSelectEntity> cityData = new ArrayList<>();

    //省
    private String areacode = "";
    //地区
    private String cityNo = "";
    private String areaName = "";
    //金额
    private String price = "";
    private String priceName = "";
    // 分类
    private String goodsType = "";
    private String goodsTypeName = "";
    private String typesNo = "";

    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    public static PickAttentionBiddingListFragment newInstance() {
        PickAttentionBiddingListFragment fragment = new PickAttentionBiddingListFragment();
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_pick_attention_bidding_list, container, false);
        return binding.getRoot();
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerPickProjectComponent
                .builder()
                .appComponent(appComponent)
                .pickProjectModule(new PickProjectModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
        initData();
    }

    private void initView() {
        // 金额
        pickMoneyPopWindow = new PickHallBidingPopWindow(getActivity());
        pickMoneyPopWindow.setBgView(binding.grayLayout);
        pickMoneyPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                price = ((PickSelectEntity) key1).getNo();
                priceName = ((PickSelectEntity) key1).getProjectscale();
                if (!"全部".equals(priceName)) {
                    isChange2 = true;
                    updateChooseTextStatus(binding.tvMoney,1,priceName);
                }else{
                    isChange2 = false;
                    priceName = "概算金额";
                    updateChooseTextStatus(binding.tvMoney,0,priceName);
                }
                initFilterData();
            }
        });
        pickMoneyPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange2) {
                    updateChooseTextStatus(binding.tvMoney,0,priceName);
                } else {
                    updateChooseTextStatus(binding.tvMoney,1,priceName);
                }
            }
        });
        categoryFilterPopWindow = new CommonCategoryFilterPopWindow(getActivity(), true);
        categoryFilterPopWindow.setBgView(binding.grayLayout);
        categoryFilterPopWindow.setResultListener(new CommonCategoryFilterPopWindow.Listener() {

            @Override
            public void setResultListener(String text, String result, String typeNo) {
                if("0".equals(typeNo)){
                    goodsType = "";
                }else{
                    goodsType = result;
                }
                goodsTypeName = text;
                typesNo = typeNo;

                if(!"全部".equals(goodsTypeName)){
                    updateChooseTextStatus(binding.tvCategory,1,goodsTypeName);
                    isChange4 = true;
                }else{
                    isChange4 = false;
                    goodsTypeName = "竞价类型";
                    updateChooseTextStatus(binding.tvCategory,0,goodsTypeName);
                }
                initFilterData();
            }

            @Override
            public void setResetResultListener() {
                goodsType = "";
                typesNo = "";
                isChange4 = false;
                goodsTypeName = "竞价类型";
                updateChooseTextStatus(binding.tvCategory,0,goodsTypeName);
            }
        });
        categoryFilterPopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
            @Override
            public void disMiss() {
                if (!isChange4) {
                    updateChooseTextStatus(binding.tvCategory,0,goodsTypeName);
                } else {
                    updateChooseTextStatus(binding.tvCategory,1,goodsTypeName);
                }
            }
        });
        categoryFilterPopWindow.setCategoryCallBack1(new CommonCategoryFilterPopWindow.CategoryCallBack1() {
            @Override
            public void resultPosition1(String posName1, String posName2, String posName3, String posName4, int pos1, int pos2, int pos3, int pos4) {

            }

            @Override
            public void setChildData(String position) {
                viewModel.getTenderGoodsCategoryAllList(position);
            }
        });
        //省
        viewModel.getProvinceData();
        //类型
        viewModel.getFilterTypeData();
        //概算金额
        viewModel.getPriceData();
        initFilterData();

        initAddressPopup();
    }

    private void initAddressPopup() {
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                areacode = entity.getProvinceNo();
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    areaName = entity.getProvinceName();
                    areacode = entity.getProvinceNo();
                    cityNo = "";
                    if ("0".equals(areacode)) {
                        areaName = "地区";
                    }
                    updateChooseTextStatus(binding.tvArea, 1, areaName);
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        cityNo = entity.getCityNo();
                        areaName = entity.getCityName();
                        viewModel.getAddressCityData(scrData, cityNo);
                        updateChooseTextStatus(binding.tvArea, 1, areaName);
                    }
                } else {
                    areaName = "地区";
                    areacode = "";
                    cityNo = "";
                    updateChooseTextStatus(binding.tvArea, 0, areaName);
                }
                initFilterData();
            }
        });

        mAddressPop.setOnDismissListener(() -> {
            updateChooseTextStatus(binding.tvArea, "地区".equals(areaName) ? 0 : 1, areaName);
        });
    }

    private void initData() {
        //新增类别
        binding.tvCategory.setOnClickListener(this);
        binding.tvMoney.setOnClickListener(this);
        binding.tvArea.setOnClickListener(this);

        if (pickingAdapter == null) {
            pickingAdapter = new PickBidingAdapter(getActivity(), null);
        }
        DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide2));
        binding.recyclerView.addItemDecoration(divider);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.setAdapter(pickingAdapter);
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                initFilterData();
            }

            @Override
            public void onLoadMore() {
                viewModel.getBiddingList(cityNo, typesNo, price, true, areacode, goodsType);
            }
        });
    }

    public void setTenderGoodsCategoryAllList(List<PickSelectEntity<List<PickSelectEntity<List<PickSelectEntity>>>>> datas) {
        categoryFilterPopWindow.setCategoryData(datas);
    }

    private void initFilterData() {
        viewModel.getBiddingList(cityNo, typesNo, price, false, areacode, goodsType);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_money:
                if (TextUtils.isEmpty(priceName)) {
                    priceName = "概算金额";
                }
                updateChooseTextStatus(binding.tvMoney, TextUtils.isEmpty(price) ? -1 : -2, priceName);
                pickMoneyPopWindow.showPopwindow0(binding.tvMoney);
                pickMoneyPopWindow.setData(priceData);
                break;
            case R.id.tv_area:
                if (TextUtils.isEmpty(areaName)) {
                    areaName = "地区";
                }
                updateChooseTextStatus(binding.tvArea, TextUtils.isEmpty(areacode) && TextUtils.isEmpty(cityNo) ? -1 : -2, areaName);
                mAddressPop.showPopwindow0(binding.tvArea);
                break;
            case R.id.tv_category:
                if (null != typeData && typeData.size() > 0) {
                    if (TextUtils.isEmpty(goodsTypeName)) {
                        goodsTypeName = "竞价类型";
                    }
                    updateChooseTextStatus(binding.tvCategory, -1, goodsTypeName);
                    if (TextUtils.isEmpty(typesNo)) {
                        typesNo = "0";
                    }
                    categoryFilterPopWindow.showPopWindow1(binding.tvCategory);
                    if (TextUtils.isEmpty(typesNo)) {
                        categoryFilterPopWindow.setData1(typeData, 0, "",true);
                    } else {
                        categoryFilterPopWindow.setData1(typeData, Integer.valueOf(typesNo), "",true);
                    }
                }
                break;
        }
    }

    public void showList(List<BiddingEntity> list, boolean isLoadMore) {
        binding.recyclerView.refreshComplete();
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() > 0) {
                pickingAdapter.addDatas(list);
            } else {
                binding.recyclerView.setLoadingMoreEnabled(false);
            }
        } else {
            binding.recyclerView.refreshComplete();
            if (list.size() > 0) {
                binding.emptyView.setVisibility(View.GONE);
                binding.recyclerView.setVisibility(View.VISIBLE);
                pickingAdapter.setDatas(list);
                binding.recyclerView.setLoadingMoreEnabled(true);
            } else {
                pickingAdapter.setDatas(new ArrayList<>());
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.recyclerView.setVisibility(View.GONE);
            }
        }
        pickingAdapter.setOnItemClick(new AdapterOnItemClick<BiddingEntity>() {
            @Override
            public void onItemClick(BiddingEntity tenderListEntity, int position) {
                viewModel.getUrlSetting(tenderListEntity.getId());
            }
        });
        pickingAdapter.onIChildClick(new PickBidingAdapter.IChildClick() {
            @Override
            public void onClick(BiddingEntity tenderListEntity) {
                viewModel.getUrlSetting(tenderListEntity.getId());
            }
        });
    }

    public void getUrl(String url, String id) {
        WebViewX5HostActivity.start(getContext(), url, id);
    }

    public void setPriceDatas(List<PickSelectEntity> datas) {
        priceData.clear();
        priceData.addAll(datas);
    }

    public void setTypeDatas(List<PickSelectEntity> datas) {
        typeData.clear();
        typeData.addAll(datas);
    }

    public void setCityDatas(List<PickSelectEntity> data) {
        cityData.clear();
        cityData.addAll(data);
        mAddressPop.setData(scrData, false);
    }

    public void setProvinceDatas(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            mAddressPop.setData(scrData, true);
        } else {
            viewModel.getAddressCityData(scrData, cityNo);
        }
    }

    /**
     * 更新选项颜色
     */
    private void updateChooseTextStatus(PickPopWindowView pickPopWindowView, int value, String name) {
        if (!TextUtils.isEmpty(name)) {
            if (name.length() > 4) {
                name = name.substring(0, 4) + "...";
            }
        }
        if (value == -1 || value == -2) {
            binding.popLine.setVisibility(View.VISIBLE);
            pickPopWindowView.setChooseData(R.drawable.member_pop_blue_bg2, R.mipmap.ic_up_arrow_n, R.color.color_333333,true,name);
        }else if (value == 0) {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_bg, R.mipmap.ic_down_arrow_n, R.color.color_333333,false,name);
        } else {
            binding.popLine.setVisibility(View.GONE);
            pickPopWindowView.setChooseData(R.drawable.search_new_blue_bg_10, R.mipmap.icon_down_red, R.color.color_main,false,name);
        }
    }
}

